package com.ruixing.newcourt;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.GsonBuilder;
import com.ruixing.newcourt.Bean.ImgBean;
import com.ruixing.newcourt.Bean.NewsBean;
import com.ruixing.newcourt.Bean.WeatherBean;
import com.ruixing.newcourt.adapter.NewsAdapter;
import com.ruixing.newcourt.utils.Content;
import com.ruixing.newcourt.utils.DateUtil;
import com.ruixing.newcourt.utils.GlideImageLoader;
import com.ruixing.newcourt.utils.ImgService;
import com.ruixing.newcourt.utils.NewsService;
import com.ruixing.newcourt.utils.WeatherService;
import com.tencent.bugly.crashreport.CrashReport;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.clock)
    TextView clock;
    @BindView(R.id.week)
    TextView week;
    @BindView(R.id.news_list)
    ListView newsList;
    @BindView(R.id.weather_date1)
    TextView weatherDate1;
    @BindView(R.id.weather_icon1)
    ImageView weatherIcon1;
    @BindView(R.id.weather_weather1)
    TextView weatherWeather1;
    @BindView(R.id.weather_temp1)
    TextView weatherTemp1;
    @BindView(R.id.weather_date2)
    TextView weatherDate2;
    @BindView(R.id.weather_icon2)
    ImageView weatherIcon2;
    @BindView(R.id.weather_weather2)
    TextView weatherWeather2;
    @BindView(R.id.weather_temp2)
    TextView weatherTemp2;
    @BindView(R.id.weather_date3)
    TextView weatherDate3;
    @BindView(R.id.weather_icon3)
    ImageView weatherIcon3;
    @BindView(R.id.weather_weather3)
    TextView weatherWeather3;
    @BindView(R.id.weather_temp3)
    TextView weatherTemp3;
    @BindView(R.id.banner)
    Banner banner;


    private WeatherBean weatherBean;
    private NewsBean newsBean;

    private final String IMAGE_URL = "http://192.168.1.102:8888/court/upload/";//滚动图片

    final static int TIMETASK = 20000;
    final static int WEATHER = 20001;
    final static int NEWS_AUTO_SLIDE = 10001;
    final static int NEWS = 10000;
    final static int VIEWPAGER_AUTO_SLIDE = 10002;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
        ButterKnife.bind(this);
        initBugly();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        handler.sendEmptyMessage(TIMETASK);
        handler.sendEmptyMessage(NEWS_AUTO_SLIDE);
        handler.sendEmptyMessage(NEWS);
        weatherInit();
        handler.sendEmptyMessage(VIEWPAGER_AUTO_SLIDE);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIMETASK:
                    Data();
                    handler.sendEmptyMessageDelayed(TIMETASK, 1000);
                    break;
                case WEATHER:
                    weatherInit();
                    break;
                case NEWS_AUTO_SLIDE:
                    newsList.smoothScrollBy(1, 0);
                    handler.sendEmptyMessageDelayed(NEWS_AUTO_SLIDE, 100);
                    break;
                case NEWS:
                    newsInit();
                    handler.sendEmptyMessageDelayed(NEWS, 600000);
                    break;
                case VIEWPAGER_AUTO_SLIDE:
                    imgInit();
                    handler.sendEmptyMessageDelayed(VIEWPAGER_AUTO_SLIDE,600000);
                    break;
            }
        }
    };

    private void Data() {
        date.setText(DateUtil.getYMD());
        clock.setText(DateUtil.getHM());
        if (DateUtil.getHM().equals("00:00:01")) {
            handler.sendEmptyMessage(WEATHER);

        }
        week.setText(DateUtil.getWeek());
    }

    private void newsInit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.wuhucourt.gov.cn/tmp/jsonp/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .build();
        NewsService service = retrofit.create(NewsService.class);
        Call<NewsBean> call = service.getSearchBook(189, 10);
        call.enqueue(new Callback<NewsBean>() {
            @Override
            public void onResponse(Call<NewsBean> call, Response<NewsBean> response) {
                newsBean = response.body();
                List<NewsBean> list = new ArrayList<>();
                list.add(newsBean);
                NewsAdapter mBaseAdapter = new NewsAdapter(getApplicationContext(), list);
                newsList.setAdapter(mBaseAdapter);
            }

            @Override
            public void onFailure(Call<NewsBean> call, Throwable t) {
            }
        });
    }

    private void weatherInit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.102:8888/court/fayuan/wechat/louyu2/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .build();
        WeatherService service = retrofit.create(WeatherService.class);
        Call<WeatherBean> call = service.getSearchBook();
        call.enqueue(new Callback<WeatherBean>() {
            @Override
            public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                weatherBean = response.body();
                weatherDate1.setText(weatherBean.getWeatherData().get(0).getDate());
                weatherIcon1.setImageDrawable(Content.getWeatherImageByCode(weatherBean.getWeatherData().get(0).getCode_day(), MainActivity.this));
                weatherTemp1.setText(weatherBean.getWeatherData().get(0).getLow() + "℃~" + weatherBean.getWeatherData().get(0).getHigh() + "℃");
                weatherWeather1.setText(weatherBean.getWeatherData().get(0).getText_day());

                weatherDate2.setText(weatherBean.getWeatherData().get(1).getDate());
                weatherIcon2.setImageDrawable(Content.getWeatherImageByCode(weatherBean.getWeatherData().get(1).getCode_day(), MainActivity.this));
                weatherTemp2.setText(weatherBean.getWeatherData().get(1).getLow() + "℃~" + weatherBean.getWeatherData().get(1).getHigh() + "℃");
                weatherWeather2.setText(weatherBean.getWeatherData().get(1).getText_day());

                weatherDate3.setText(weatherBean.getWeatherData().get(2).getDate());
                weatherIcon3.setImageDrawable(Content.getWeatherImageByCode(weatherBean.getWeatherData().get(2).getCode_day(), MainActivity.this));
                weatherTemp3.setText(weatherBean.getWeatherData().get(2).getLow() + "℃~" + weatherBean.getWeatherData().get(2).getHigh() + "℃");
                weatherWeather3.setText(weatherBean.getWeatherData().get(2).getText_day());
            }

            @Override
            public void onFailure(Call<WeatherBean> call, Throwable t) {
            }
        });
    }

    private void imgInit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.102:8888/court/fayuan/wechat/louyuAdvertise/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .build();
        ImgService service = retrofit.create(ImgService.class);
        Call<List<ImgBean>> call = service.getSearch();
        call.enqueue(new Callback<List<ImgBean>>() {
            @Override
            public void onResponse(Call<List<ImgBean>> call, Response<List<ImgBean>> response) {

                 List<ImgBean> imgBeanList = new ArrayList<>();
                 List<String> imgList = new ArrayList<>();

                imgBeanList = response.body();
                for (int i = 0; i < imgBeanList.size(); i++){
                    imgList.add(IMAGE_URL + imgBeanList.get(i).getImgurl());
                }
                Banner banner = (Banner) findViewById(R.id.banner);
                //设置图片加载器
                banner.setImageLoader(new GlideImageLoader());
                banner.setBannerStyle(BannerConfig.NOT_INDICATOR);//去除圆点
                //设置图片集合
                banner.setImages(imgList);
                banner.setDelayTime(3000);//设置轮播时间
                //banner设置方法全部调用完毕时最后调用
                banner.start();
            }

            @Override
            public void onFailure(Call<List<ImgBean>> call, Throwable t) {

            }
        });

    }

    /**
     * 初始化腾讯bug管理平台
     */
    private void initBugly() {
        /* Bugly SDK初始化
         * 参数1：上下文对象
         * 参数2：APPID，平台注册时得到,注意替换成你的appId
         * 参数3：是否开启调试模式，调试模式下会输出'CrashReport'tag的日志
         * 注意：如果您之前使用过Bugly SDK，请将以下这句注释掉。
         */
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
        strategy.setAppVersion(getApplicationContext().getPackageName());
        strategy.setAppReportDelay(200);                          //Bugly会在启动0.2s后联网同步数据

        /*  第三个参数为SDK调试模式开关，调试模式的行为特性如下：
            输出详细的Bugly SDK的Log；
            每一条Crash都会被立即上报；
            自定义日志将会在Logcat中输出。
            建议在测试阶段建议设置成true，发布时设置为false。*/

        CrashReport.initCrashReport(getApplicationContext(), "decdb6de5c", true ,strategy);

        //Bugly.init(getApplicationContext(), "1374455732", false);
    }

}
